package com.pzl.util;

import android.app.AlarmManager;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日期格式化对象
 */
public class DateUtil {

    public static final String DATE_FORMAT_DAY = "yyyy-MM-dd";

    public static final String DATE_FORMAT_MONTH = "yyyy-MM";

    public static final String DATE_FORMAT_HOUR = "yyyy-MM-dd HH";

    public static final String DATE_FORMAT_MINUTE = "yyyy-MM-dd HH:mm";
    public static final String DATE_FORMAT_MINUTE_POINT = "yyyy.MM.dd HH:mm";

    public static final String DATE_FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_SECOND_POINT = "yyyy.MM.dd HH:mm:ss";

    public static final String DATE_FORMAT_MILLISECOND = "yyyy-MM-dd HH:mm:ss.SSS";

    public static final String DATE_FORMAT_CHINESE = "yyyy年MM月dd日";

    public static final String DATE_FORMAT_MINUTE_CHINESE = "yyyy年MM月dd日HH时mm分";

    public static final String DATE_FORMAT_MILLISECOND_NO = "yyyyMMddHHmmssSSS";

    public static final String DATE_FORMAT_SPRIT = "dd/MM/yyyy";

    public static final String DATE_FORMAT_DAY_POINT = "yyyy.MM.dd";
    public static final String DATE_FORMAT_MONTH_2 = "yyyyMM";

    public static final String DATE_FORMAT_MONTH_DAY_POINT = "M.d";
    public static final String DATE_FORMAT_MONTH_DAY_POINT_24 = "MM.dd";
    public static final String DATE_FORMAT_TIME_POINT_24 = "HH:mm:ss";

    public static final String DATE_FORMAT_DAY_TIME_POINT = "H:mm";

    public static final String DATE_FORMAT_SPRIT_MINUTE = "HH:mm yyyy/dd/MM";
    public static final String DATE_FORMAT_IMPORT = "MM/dd/yyyy HH:mm:ss";

    public static final String TIME_ON_WORK = " 08:00:00";
    public static final String TIME_OFF_WORK = " 18:00:00";

    /**
     * 某一时间在指定的时间段内
     */
    public static final String TIME_SCOPE_BEGIN = " 08:30:00";   //某时间段的开始时间
    public static final String TIME_SCOPE_END = " 17:30:00";    //某时间段的结束时间

    public static int getWeekDay() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.DAY_OF_WEEK) - 1;
    }

    public static int getMonthDay() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取系统当前时间long型
     *
     * @return
     */
    public static long getCurrentDateTime() {
        return new Date().getTime();
    }

    /**
     * 获取系统当前时间long型
     *
     * @return
     */
    public static long getCurrentTimeMillis() {
        return System.currentTimeMillis();
    }

    /**
     * 返回当前时间
     *
     * @return 返回当前时间
     */
    public static Date getCurrentDate() {
        Calendar calNow = Calendar.getInstance();
        return calNow.getTime();
    }

    /**
     * 获取当前时间String类型
     *
     * @return
     */
    public static String getCurrentTime() {
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MILLISECOND);
        String str = format.format(new Date());
        return str;
    }

    public static Long getDateToLong(String str) {
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy年MM月dd日").parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();
    }

    public static Long getDateToLong(String str, String pattern) {
        Date date = null;
        try {
            date = new SimpleDateFormat(pattern).parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();
    }

    public static String formatTimestamp(Timestamp timestamp) {
        return new SimpleDateFormat(DATE_FORMAT_DAY).format(timestamp);
    }

    /**
     * 格式化日期时间到秒
     *
     * @return
     */
    public static String formatDateOfSecond() {
        return new SimpleDateFormat(DATE_FORMAT_SECOND).format(new Date());
    }

    /**
     * 格式化日期时间到秒
     *
     * @return
     */
    public static String getCurrentDate(String pattern) {
        return new SimpleDateFormat(pattern).format(new Date());
    }

    public static String formatDateForChinese() {
        return new SimpleDateFormat(DATE_FORMAT_MINUTE_CHINESE).format(new Date());
    }


    /**
     * 格式化日期带毫秒数
     *
     * @return
     */
    public static String formatDateAndMillisecond() {
        return new SimpleDateFormat(DATE_FORMAT_MILLISECOND).format(new Date());
    }

    /**
     * 格式化日期：年月日
     *
     * @return
     */
    public static String formatDate() {
        return new SimpleDateFormat(DATE_FORMAT_DAY).format(new Date());
    }

    /**
     * 格式化日期：年月日
     *
     * @return
     */
    public static String formatDate(long l) {
        return new SimpleDateFormat(DATE_FORMAT_DAY).format(new Date(l));
    }

    /**
     * 格式化日期：年月日
     *
     * @return
     */
    public static String formatDate(Date date) {
        if (date == null)
            return "";
        return new SimpleDateFormat(DATE_FORMAT_DAY).format(date);
    }

    /**
     * 格式化日期：年月日
     *
     * @return
     */
    public static String formatDate(Date date, String pattern) {
        if (date == null)
            return "";
        return new SimpleDateFormat(pattern).format(date);
    }

    /**
     * 格式化日期：年月日
     *
     * @return
     */
    public static String formatDate(String str, String pattern1, String pattern2) {
        if (TextUtils.isEmpty(str))
            return "";
        SimpleDateFormat sdf = new SimpleDateFormat(pattern1);
        Date date = null;
        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new SimpleDateFormat(pattern2).format(date);
    }

    /**
     * 格式化日期：年月日
     *
     * @return
     */
    public static String formatDate(Long date, String pattern) {
        if (date == null)
            return "";
        return new SimpleDateFormat(pattern).format(date);
    }

    /**
     * 格式化日期：年月日 时
     *
     * @param l
     * @return
     */
    public static String formatDateTime(long l) {
        return new SimpleDateFormat(DATE_FORMAT_HOUR).format(new Date(l));
    }

    /**
     * 格式化日期：年月日 时分
     *
     * @param l
     * @return
     */
    public static String formatDateTimeminute(long l) {
        return new SimpleDateFormat(DATE_FORMAT_MINUTE).format(new Date(l));
    }

    /**
     * 格式化日期：年月日 时分秒
     *
     * @param l
     * @return
     */
    public static String formatDateTimesecond(long l) {
        return new SimpleDateFormat(DATE_FORMAT_SECOND).format(new Date(l));
    }

    /**
     * 格式化日期：年月日 时分秒
     *
     * @param date
     * @return
     */
    public static String formatDateTimesecond(Date date) {
        if (date == null)
            return "";
        return new SimpleDateFormat(DATE_FORMAT_SECOND).format(date);
    }

    /**
     * 格式化日期：年月日 时分秒
     *
     * @param date
     * @return
     */
    public static String formatDateTimesecond(Date date, String pattern) {
        if (date == null)
            return "";
        return new SimpleDateFormat(pattern).format(date);
    }

    /**
     * 格式化日期：年月日
     *
     * @param date
     * @return
     */
    public static String formatDate(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        try {
            Date d = sdf.parse(date);
            return new SimpleDateFormat(DATE_FORMAT_DAY).format(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date formatDateByString(String strDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        try {
            return sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date parseMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_MONTH);
        try {
            return sdf.parse(sdf.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date parseDateTime(String strDate) {
        if (strDate == null || "".equals(strDate)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_SECOND);
        try {
            return sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date parseDate(String strDate) {
        if (strDate == null || "".equals(strDate)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DAY);
        try {
            return sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date parseDate(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DAY);
        try {
            return sdf.parse(sdf.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date parseDate(String strDate, String pattern) {
        if (strDate == null || "".equals(strDate)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 格式化日期：时分秒
     *
     * @return
     */
    public static String formatTime() {
        return new SimpleDateFormat("HH:mm:ss").format(new Date());
    }

    /**
     * 1.图片命名，精确到毫秒
     *
     * @return
     */
    public static String picMillisecondName() {
        return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    }

    /**
     * 1.图片命名，精确到秒
     *
     * @return
     */
    public static String picSecondName() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

    /**
     * 1.图片命名，精确到秒
     *
     * @return
     */
    public static String fileDayName() {
        return new SimpleDateFormat("yyyyMMdd").format(new Date());
    }

    /**
     * 计算某年某月某日某点到当日的天数
     *
     * @return
     */
    public static int calDays(String s) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_SECOND);
        long l = 0l;
        try {
            l = (new Date()).getTime() - (sdf.parse(s)).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (int) (l / 1000 / 60 / 60 / 24);
    }

    /**
     * 比较日期的大小；当天之前：-1，当天：0，当天以后：1+.
     *
     * @param sqlDate
     * @return
     */
    public static int compareToDate(String sqlDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String temp = null;
        try {
            if (sqlDate != null && !sqlDate.equals("")) {
                temp = sdf.format(sdf.parse(sqlDate));
            } else {
                return 1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return temp.compareTo(sdf.format(new Date()));
    }

    /**
     * 比较日期的大小；当天之前：-1，当天：0，当天以后：1+.
     *
     * @param sqlDate
     * @param pattern
     * @return
     */
    public static int compareToDateForPattern(String sqlDate, String pattern) {
        if (TextUtils.isEmpty(sqlDate)) {
            return -1;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sqlDate.compareTo(sdf.format(new Date()));
    }

    /**
     * 比较日期的大小；当天之前：-1，当天：0，当天以后：1+.
     *
     * @param firstDate
     * @param secondDate
     * @return
     */
    public static int compareToDate(String firstDate, String secondDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String temp1 = null;
        String temp2 = null;
        try {
            if (firstDate != null && !firstDate.equals("")) {
                temp1 = sdf.format(sdf.parse(firstDate));
            } else {
                return 1;
            }
            if (secondDate != null && !secondDate.equals("")) {
                temp2 = sdf.format(sdf.parse(secondDate));
            } else {
                return 1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return temp1.compareTo(temp2);
    }

    /**
     * 比较日期的大小；当天之前：-1，当天：0，当天以后：1+.
     *
     * @param sqlDate
     * @return
     */
    public static int compareToDate(Long sqlDate) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DAY);
        String temp = null;
        if (sqlDate != null && !sqlDate.equals("")) {
            temp = sdf.format(new Date(sqlDate));
        } else {
            return 1;
        }
        return temp.compareTo(sdf.format(new Date()));
    }

    /**
     * 比较日期的大小；当天之前：-1，当天：0，当天以后：1+.
     *
     * @param historyDate
     * @return
     */
    public static int checkHistoryDate(Long historyDate) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DAY);
        String temp = null;
        if (historyDate != null && !historyDate.equals("")) {
            temp = sdf.format(new Date(historyDate));
        } else {
            return -1;
        }
        return temp.compareTo(sdf.format(new Date()));
    }

    /**
     * 判断某一时间是否在指定的时间段内(包含与起止时间相等的情况)
     *
     * @param time
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean betweenScope(Timestamp time, Timestamp beginTime, Timestamp endTime) {
        return (!time.before(beginTime) && !time.after(endTime));
    }

    /**
     * 判断某一时间是否在指定的时间段内(包含与起止时间相等的情况)
     *
     * @param date
     * @param beginDate
     * @param endDate
     * @return
     */
    public static boolean betweenScope(Date date, Date beginDate, Date endDate) {
        return (!date.before(beginDate) && !date.after(endDate));
    }

    /**
     * 判断某一时间是否在指定的时间段内(包含与起止时间相等的情况)
     *
     * @param date
     * @param beginDate
     * @param endDate
     * @return
     */
    public static boolean betweenScope(Date date, String beginDate, String endDate) {
        return (!date.before(parseDate(beginDate)) && !date.after(parseDate(endDate)));
    }

    /**
     * 判断某一时间是否在指定的时间段内(包含与起止时间相等的情况)
     *
     * @param date
     * @param beginDate
     * @param endDate
     * @return
     */
    public static boolean betweenScope(Date date, String beginDate, String endDate, String pattern) {
        return (!date.before(parseDate(beginDate, pattern)) && !date.after(parseDate(endDate, pattern)));
    }

    /**
     * 判断某一时间是否在指定的时间段内(包含与起止时间相等的情况)
     *
     * @param date
     * @param beginDate
     * @param endDate
     * @return
     */
    public static boolean betweenScope(String date, String beginDate, String endDate) {
        return betweenScope(parseDate(date), beginDate, endDate);
    }

    /**
     * 判断某一时间是否在指定的时间段内(包含与起止时间相等的情况)
     *
     * @param date
     * @param beginDate
     * @param endDate
     * @param pattern
     * @return
     */
    public static boolean betweenScope(String date, String beginDate, String endDate, String pattern) {
        return betweenScope(parseDate(date, pattern), beginDate, endDate);
    }

    /**
     * 判断某一时间是否在指定的时间段内(包含与起止时间相等的情况)
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    public static boolean compareDate(Date beginDate, Date endDate) {
        return !beginDate.after(endDate);
    }

    /**
     * 判断某一时间是否在指定的时间之后(包含与指定时间相等的情况)
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    public static boolean compareDate(String beginDate, Date endDate) {
        if ("".equals(beginDate) || beginDate == null) {
            return false;
        }
        return compareDate(parseDate(beginDate), endDate);
    }

    public static boolean compareDate(String beginDate, String endDate) {
        if ("".equals(beginDate) || beginDate == null) {
            return false;
        }
        return compareDate(parseDate(beginDate), parseDate(endDate));
    }

    public static boolean compareDate(String beginDate, String endDate, String pattern) {
        if ("".equals(beginDate) || beginDate == null) {
            return false;
        }
        return compareDate(parseDate(beginDate, pattern), parseDate(endDate, pattern));
    }

    public static boolean compareDate(long beginDate, long endDate) {
        return beginDate < endDate;
    }

    /**
     * 判断某一时间是否在指定的时间段内(包含与起止时间相等的情况)
     *
     * @return
     */
    public static boolean betweenScope() {
        Timestamp time = new Timestamp(System.currentTimeMillis());
        String currentDate = time.toString().substring(0, 10);
        String begin = currentDate + TIME_SCOPE_BEGIN;
        String end = currentDate + TIME_SCOPE_END;
        Timestamp beginTime = Timestamp.valueOf(begin);
        Timestamp endTime = Timestamp.valueOf(end);
        return (!time.before(beginTime) && !time.after(endTime));
    }

    public static Timestamp dateToTimestamp(Date date) {
        return new Timestamp(date.getTime());
    }

    /**
     * String-->Timestamp, String的类型必须为：yyyy-MM-dd hh:mm:ss[.f...] 这样的格式，中括号表示可选，否则报错
     *
     * @param s
     * @return
     */
    public static Timestamp stringToTimestamp(String s) {
        return Timestamp.valueOf(s);
    }

    public static String timestampToString(Timestamp timestamp, String pattern) {
        return new SimpleDateFormat(pattern).format(timestamp);
    }


    public static Date formatDateToMinuteByString(String strDate) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_MINUTE_CHINESE);
        try {
            return sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Date formatDateToDayByString(String strDate) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_CHINESE);
        try {
            return sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String formatDateToMinute(Date date) {
        if (date == null)
            return "";
        return new SimpleDateFormat(DATE_FORMAT_MINUTE_CHINESE).format(date);
    }

    /**
     * 返回在那天增加天数之后的日期
     *
     * @param srcDate
     * @param days
     * @return
     */
    public static Date addDays(Date srcDate, int days) {
        Calendar c = Calendar.getInstance();
        c.setTime(srcDate);
        c.add(Calendar.DAY_OF_MONTH, days); //表示加了的天数
        return c.getTime();
    }

    /**
     * 日期增加-按日增加
     *
     * @param date
     * @param days
     * @return java.util.Date
     */
    public static Date dateIncreaseByDay(Date date, int days) {
        Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
        cal.setTime(date);
        cal.add(Calendar.DATE, days);

        return cal.getTime();
    }


    /**
     * 两个long型时间相减，得到天、时、分
     *
     * @param howlong
     * @return
     */
    public static String consueTime(Long howlong) {
        long nd = 1000 * 24 * 60 * 60;//一天的毫秒数
        long nh = 1000 * 60 * 60;//一小时的毫秒数
        long nm = 1000 * 60;//一分钟的毫秒数
        long ns = 1000;//一秒钟的毫秒数long

        long day = howlong / nd;//计算差多少天
        long hour = howlong % nd / nh;//计算差多少小时
        long min = howlong % nd % nh / nm;//计算差多少分钟
        long sec = howlong % nd % nh % nm / ns;//计算差多少秒//输出结果
        String consum = (day == 0 ? "" : day + "天") + (hour == 0 ? "" : hour + "小时") + (min == 0 ? "" : min + "分钟") + (sec == 0 ? "" : sec + "秒");
        return consum;
    }


    public static Long getStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime().getTime();
    }

    public static Long getEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime().getTime();
    }

    /**
     * 将指定的日期转换为一定格式的字符串
     *
     * @param date   the date
     * @param format the format
     * @return string string
     */
    public static String toDateString(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
        return sdf.format(date);
    }

    /**
     * 将当前的日期转换为一定格式的字符串
     *
     * @param format the format
     * @return string string
     */
    public static String toDateString(String format) {
        return toDateString(Calendar.getInstance(Locale.CHINA).getTime(), format);
    }

    /**
     * 将指定的日期字符串转换为日期时间
     *
     * @param dateStr 如：2014-04-08 23:02
     * @return date date
     */
    public static Date toDate(String dateStr) {
        return DateUtil.parseDate(dateStr);
    }

    /**
     * 将指定的日期字符串转换为时间戳
     *
     * @param dateStr 如：2014-04-08 23:02
     * @return long long
     */
    public static long toTimemillis(String dateStr) {
        return toDate(dateStr).getTime();
    }

    /**
     * Calculate days in month int.
     *
     * @param year  the year
     * @param month the month
     * @return the int
     */
    public static int calculateDaysInMonth(int year, int month) {
        // 添加大小月月份并将其转换为list,方便之后的判断
        String[] bigMonths = {"1", "3", "5", "7", "8", "10", "12"};
        String[] littleMonths = {"4", "6", "9", "11"};
        List<String> bigList = Arrays.asList(bigMonths);
        List<String> littleList = Arrays.asList(littleMonths);
        // 判断大小月及是否闰年,用来确定"日"的数据
        if (bigList.contains(String.valueOf(month))) {
            return 31;
        } else if (littleList.contains(String.valueOf(month))) {
            return 30;
        } else {
            if (year <= 0) {
                return 29;
            }
            // 是否闰年
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                return 29;
            } else {
                return 28;
            }
        }
    }

    /**
     * 月日时分秒，0-9前补0
     *
     * @param number the number
     * @return the string
     */
    @NonNull
    public static String fillZero(int number) {
        return number < 10 ? "0" + number : "" + number;
    }

    /**
     * 功能：判断日期是否和当前date对象在同一天。
     * 参见：http://www.cnblogs.com/myzhijie/p/3330970.html
     *
     * @param date 比较的日期
     * @return boolean 如果在返回true，否则返回false。
     * @author 沙琪玛 QQ：862990787 Aug 21, 2013 7:15:53 AM
     */
    public static boolean isSameDay(Date date) {
        if (date == null) {
            throw new IllegalArgumentException("date is null");
        }
        Calendar nowCalendar = Calendar.getInstance();
        Calendar newCalendar = Calendar.getInstance();
        newCalendar.setTime(date);
        return (nowCalendar.get(Calendar.ERA) == newCalendar.get(Calendar.ERA) &&
                nowCalendar.get(Calendar.YEAR) == newCalendar.get(Calendar.YEAR) &&
                nowCalendar.get(Calendar.DAY_OF_YEAR) == newCalendar.get(Calendar.DAY_OF_YEAR));
    }

    /**
     * 获取当前时间为每年第几周
     *
     * @param date
     * @return
     */
    public static int getWeekOfYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        int week = c.get(Calendar.WEEK_OF_YEAR) - 1;
        week = week == 0 ? 52 : week;
        return week > 0 ? week : 1;
    }

    /**
     * format time friendly
     *
     * @param sdate YYYY-MM-DD HH:mm:ss
     * @return n分钟前, n小时前, 昨天, 前天, n天前, n个月前
     */
    public static String formatSomeAgo(String sdate) {
        if (sdate == null) return "";
        Calendar calendar = parseCalendar(sdate);
        if (calendar == null) return sdate;

        Calendar mCurrentDate = Calendar.getInstance();
        long crim = mCurrentDate.getTimeInMillis(); // current
        long trim = calendar.getTimeInMillis(); // target
        long diff = crim - trim;

        int year = mCurrentDate.get(Calendar.YEAR);
        int month = mCurrentDate.get(Calendar.MONTH);
        int day = mCurrentDate.get(Calendar.DATE);

        if (diff < 60 * 1000) {
            return "刚刚";
        }
        if (diff >= 60 * 1000 && diff < AlarmManager.INTERVAL_HOUR) {
            return String.format("%s分钟前", diff / 60 / 1000);
        }
        mCurrentDate.set(year, month, day, 0, 0, 0);
        if (trim >= mCurrentDate.getTimeInMillis()) {
            return String.format("%s小时前", diff / AlarmManager.INTERVAL_HOUR);
        }
        mCurrentDate.set(year, month, day - 1, 0, 0, 0);
        if (trim >= mCurrentDate.getTimeInMillis()) {
            return "昨天";
        }
        mCurrentDate.set(year, month, day - 2, 0, 0, 0);
        if (trim >= mCurrentDate.getTimeInMillis()) {
            return "前天";
        }
        if (diff < AlarmManager.INTERVAL_DAY * 30) {
            return String.format("%s天前", diff / AlarmManager.INTERVAL_DAY);
        }
        if (diff < AlarmManager.INTERVAL_DAY * 30 * 12) {
            return String.format("%s月前", diff / (AlarmManager.INTERVAL_DAY * 30));
        }
        return String.format("%s年前", mCurrentDate.get(Calendar.YEAR) - calendar.get(Calendar.YEAR));
    }

    /**
     * YYYY-MM-DD HH:mm:ss格式的时间字符串转换为{@link Calendar}类型
     *
     * @param str YYYY-MM-DD HH:mm:ss格式字符串
     * @return {@link Calendar}
     */
    public static Calendar parseCalendar(String str) {
        Matcher matcher = Pattern.compile(
                "([0-9]{4})-([0-9]{2})-([0-9]{2})[\\s]+([0-9]{2}):([0-9]{2}):([0-9]{2})"
        ).matcher(str);
        Calendar calendar = Calendar.getInstance();
        if (!matcher.find()) return null;
        calendar.set(
                matcher.group(1) == null ? 0 : Integer.parseInt(matcher.group(1)),
                matcher.group(2) == null ? 0 : Integer.parseInt(matcher.group(2)) - 1,
                matcher.group(3) == null ? 0 : Integer.parseInt(matcher.group(3)),
                matcher.group(4) == null ? 0 : Integer.parseInt(matcher.group(4)),
                matcher.group(5) == null ? 0 : Integer.parseInt(matcher.group(5)),
                matcher.group(6) == null ? 0 : Integer.parseInt(matcher.group(6))
        );
        return calendar;
    }

    /**
     * @param str YYYY-MM-DD HH:mm:ss string
     * @return 今天, 昨天, 前天, n天前
     */
    public static String formatSomeDay(String str) {
        return formatSomeDay(parseCalendar(str));
    }

    /**
     * @param calendar {@link Calendar}
     * @return 今天, 昨天, 前天, n天前
     */
    public static String formatSomeDay(Calendar calendar) {
        if (calendar == null) return "?天前";
        Calendar mCurrentDate = Calendar.getInstance();
        long crim = mCurrentDate.getTimeInMillis(); // current
        long trim = calendar.getTimeInMillis(); // target
        long diff = crim - trim;

        int year = mCurrentDate.get(Calendar.YEAR);
        int month = mCurrentDate.get(Calendar.MONTH);
        int day = mCurrentDate.get(Calendar.DATE);

        mCurrentDate.set(year, month, day, 0, 0, 0);
        if (trim >= mCurrentDate.getTimeInMillis()) {
            return "今天";
        }
        mCurrentDate.set(year, month, day - 1, 0, 0, 0);
        if (trim >= mCurrentDate.getTimeInMillis()) {
            return "昨天";
        }
        mCurrentDate.set(year, month, day - 2, 0, 0, 0);
        if (trim >= mCurrentDate.getTimeInMillis()) {
            return "前天";
        }
        return String.format("%s天前", diff / AlarmManager.INTERVAL_DAY);
    }

    /**
     * 智能格式化
     */
    public static String friendly_time3(String sdate) {
        Calendar calendar = parseCalendar(sdate);
        if (calendar == null) return sdate;

        Calendar mCurrentDate = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        String s = hour >= 0 && hour < 12 ? "上午" : "下午";
        s += " HH:mm";

        if (mCurrentDate.get(Calendar.DATE) == calendar.get(Calendar.DATE)) {
            formatter.applyPattern(s);
        } else if (mCurrentDate.get(Calendar.DATE) - calendar.get(Calendar.DATE) == 1) {
            formatter.applyPattern("昨天 " + s);
        } else if (mCurrentDate.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)) {
            formatter.applyPattern("MM-dd " + s);
        } else {
            formatter.applyPattern("yyyy-MM-dd " + s);
        }
        return formatter.format(calendar.getTime());
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(today);
            String timeDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(time);
            if (nowDate.equals(timeDate)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否是相同的一天
     *
     * @param sdate1 sdate1
     * @param sdate2 sdate2
     * @return
     */
    public static boolean isSameDay(String sdate1, String sdate2) {
        if (TextUtils.isEmpty(sdate1) || TextUtils.isEmpty(sdate2)) {
            return false;
        }
        Date date1 = toDate(sdate1);
        Date date2 = toDate(sdate2);
        if (date1 != null && date2 != null) {
            String d1 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(date1);
            String d2 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(date2);
            if (d1.equals(d2)) {
                return true;
            }
        }
        return false;
    }

    /***
     * 计算两个时间差，返回的是的秒s
     *
     * @param date1
     * @param date2
     * @return
     * @author 火蚁 2015-2-9 下午4:50:06
     */
    public static long calDateDifferent(String date1, String date2) {
        try {
            Date d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).parse(date1);
            Date d2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).parse(date2);
            // 毫秒ms
            long diff = d2.getTime() - d1.getTime();
            return diff / 1000;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}
